#!/usr/bin/env python
# coding=utf-8
# @Software: PyCharm

from os import path
from PIL import Image
import argparse
import pathlib
import pystray
import logging

logger = logging.getLogger(__name__)
def make_ico_file(src_image_file, dist_ico_file, size_list=None):
    """
    :param src_image_file:
    :param dist_ico_file:
    :return:
    """
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    logger.info(f"Source image file: {src_image_file}")
    logger.info(f"Destination ICO file: {dist_ico_file}")
    if dist_ico_file is None:
        dist_ico_file = 'favicon.ico'
    default_size_list = [
        (256, 256),
        (128, 128),
        (64, 64),
        (48, 48),
        (32, 32),
        (24, 24),
        (16, 16)
    ]
    size_list = size_list or default_size_list
    src_image_file_path = pathlib.Path(src_image_file)
    if not src_image_file_path.exists():
        raise FileNotFoundError(
            f"Source image file '{src_image_file}' does not exist.")
    image_file = Image.open(src_image_file_path)
    original_image_dir = src_image_file_path.parent
    logger.info(f"Original image directory: {original_image_dir}")
    logger.info(f"Distination ICO file path: {dist_ico_file}")

    dist_ico_file_path = pathlib.Path(original_image_dir) / "target"
    logger.info(f"Destination ICO file path: {dist_ico_file_path}")
    dist_ico_file_path.mkdir(parents=True, exist_ok=True)
    dist_ico_filename = path.basename(dist_ico_file).split('.')[0]
    logger.info(f"Destination ICO file name: {dist_ico_filename}")
    for size in size_list:
        dist_ico_sized_file_name = dist_ico_file_path / \
            f"{dist_ico_filename}__{size[0]}_{size[1]}.ico"
        print(f"Saving ICO file: {dist_ico_sized_file_name}", end='\r')
        image = image_file.resize(size, Image.Resampling.LANCZOS)
        image.save(dist_ico_sized_file_name, format='ICO', sizes=[size])
        print(size, end='\r')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Convert image to ICO format.')
    parser.add_argument('src_image_file', type=str,
                        help='Source image file path')
    parser.add_argument('--dest', type=str,
                        help='Destination ICO file path', required=False)
    parser.add_argument('--keep-filename', type=bool, default=False)
    args = parser.parse_args()
    logger.info(args)
    make_ico_file(
        src_image_file=args.src_image_file,
        dist_ico_file=args.dest
        if "dest" in args else 'favicon.ico' if not args.keep_filename else args.src_image_file.split('.')[0] + '.ico')
